'use strict';

angular.module('wb-tea.controllers', []).controller('DashCtrl', function ($scope, $rootScope, $state, HttpService, $ionicPlatform, UserService, MsgService) {
	$scope.recTeaInit = function () {
		var user = UserService.getUserAcceptCache();
		var param = '';
		if (user)param={user_id:user.id};

		var callback = {
			success: function success(result) {
				$scope.recList = result.result;
				$scope.isStop_scroll = false;
				console.log($scope.recList);
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'product/list', params: param, callback: callback });
	};

	//推荐商品分页
	$scope.currPage = 1;
	$scope.isStop_scroll = true;
	$scope.scroll_load_product = function(){

		$scope.currPage += 1;
		var param = {
			page:$scope.currPage
		};

		var user = UserService.getUserAcceptCache();
		if (user)param.user_id = user.id;

		var callback = {
			success: function success(result) {
				console.log($scope.recList);
				var length = result.result.length;
				if(length == 0){
					$scope.isStop_scroll = true;
					return;
				}
				for(var i=0;i<length;i++){
					$scope.recList.push(result.result[i]);
				}
				$scope.$broadcast('scroll.infiniteScrollComplete');
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'product/list', params: param, callback: callback });
	}

	$scope.isShowFlag = function(item, position) {
		if (item.certificate.indexOf(position.toString()) == -1) {
			return false;
		} else {
			return true;
		}
	}

	//妈的会出奇怪页面bug  只好用无语的办法
	$scope.is_vote = function(isUpvote,productId){
		if(isUpvote){
			$scope.upvote_cancel(productId);
		}else{
			$scope.upvote2(productId);
		}
	}

	//商品点赞
	$scope.upvote2 = function(productId){
		var user = UserService.getUserAcceptCache();
		if (!user) return;

		var param = {
			product_id: productId,
			user_id: user.id
		}
		console.log("商品点赞参数："+JSON.stringify(param));

		var callback = {
			success: function success(result) {
				console.log("商品点赞：");
				console.log(result);
				if(result.code == '200'){
					var length = $scope.recList.length;
					for(var i=0;i<length;i++){
						 if($scope.recList[i].id == productId){
						 	$scope.recList[i].is_upvote = true;
						 	$scope.recList[i].upvote_count += 1;
						 }
					}
				}
			},
			failed:function(msg){
				console.log("点赞失败返回："+msg);
			}

		};

		HttpService({ name: 'product/upvote', params: param, callback: callback });
	}


	//取消点赞
	$scope.upvote_cancel = function(productId){
		var user = UserService.getUserAcceptCache();
		if (!user) return;
		var param = {
			product_id:productId,
			user_id:user.id
		}
		console.log("商品点赞参数："+JSON.stringify(param));

		var callback = {
			success: function success(result) {
				console.log("商品点赞取消：");
				console.log(result);
				var length = $scope.recList.length;
				for(var i=0;i<length;i++){
					 if($scope.recList[i].id == productId){
					 	$scope.recList[i].is_upvote = false;
					 	$scope.recList[i].upvote_count -= 1;
					 	if($scope.recList[i].upvote_count < 0)$scope.recList[i].upvote_count = 0;
					 }
				}
			}
		};

		HttpService({ name: 'product/upvote/cancel', params: param, callback: callback });
	}


	ionic.Platform.ready(function () {

		$rootScope.newMessage = 0;
		$rootScope.newGroupMessage = 0;

		$rootScope.unreadCallback = {
			success: function success(msg, group) {
				console.log('unreadCallback success msg = ' + msg + ' group = ' + group);
				$rootScope.changeNewMsg(msg, group);
			}
		};

		var get_newData_count = function(){
			var user = UserService.getUserAcceptCache();
			if (user == null) return;

			var callback = {
				success: function success(data) {
					console.log("查询新通知数量返回：");console.log(data);
					$rootScope.unreadNotifyMessage = data.new_message_count + data.new_notification_count;
				}
			};
			HttpService({ name: 'notification/newdata', params: {user_id: user.id}, callback: callback });
		}
		get_newData_count();

		var initCallback = {
			success: function success() {
				$rootScope.getUnreadNumber();
				$rootScope.setListener();
			}
		}

		$rootScope.getUnreadNumber = function() {
			console.log('$rootScope.getUnreadNumber');
			MsgService.getUnreadNumber($rootScope.unreadCallback);
		};

		MsgService.initRongCloud(initCallback);

		$rootScope.changeNewMsg = function(msg, group) {
			// add msgs
      		$scope.$apply(function () {
      			$rootScope.newMessage = msg;
						$rootScope.newGroupMessage = group;
      		});

		};

		// listeners
		$rootScope.newMsgReceiver = [];

		$rootScope.addReceiver = function(receiverModel) {
			console.log('add listener ' + receiverModel.name);
			var hasSame = false;
			var samePos = -1;
			for(var pos=0; pos<$rootScope.newMsgReceiver.length; pos++) {
					if (receiverModel.name == $rootScope.newMsgReceiver[pos].name) {
						hasSame = true;
						samePos = pos;
						console.log('hasSame pos = ' + samePos);
						break;
					}
			}

			if (hasSame) {
				$rootScope.newMsgReceiver.splice(samePos, 1);
			}

			console.log('add listener success now $rootScope.newMsgReceiver.length = ' + $rootScope.newMsgReceiver.length);
			$rootScope.newMsgReceiver.push(receiverModel);

		};

		// set global receiver
		$rootScope.globalMsgReceiver = function (ret, err) {

			console.log('new msg');

			if (err) {
			  console.log(JSON.stringify(err));
			  return;
			}

			MsgService.getUnreadNumber($rootScope.unreadCallback);

			for(var pos=0; pos<$rootScope.newMsgReceiver.length; pos++) {
				$rootScope.newMsgReceiver[pos].receiver(ret);
			}

			// $scope.$apply(function () {
			//   // pull conversationList for unread
			//
			// });

		};

		// if (MsgService.isConnected) {

		// }

		$rootScope.setListener = function() {
			console.log('set onReceiveListener');
			RongCloudLibPlugin.setOnReceiveMessageListener($rootScope.globalMsgReceiver);
		};

		// Disable BACK button on home
		  $ionicPlatform.registerBackButtonAction(function (event) {
		    if($state.current.name.indexOf('tab') != -1){
		      ionic.Platform.exitApp(); // stops the app
		    }
		    else {
		      $state.backToLastView();
		    }
		  }, 100);

  	// 	$rootScope.$on("$stateChangeSuccess",  function(event, toState, toParams, fromState, fromParams) {
			// if ($rootScope.hasReceiver == false) {
			// 	RongCloudLibPlugin.setOnReceiveMessageListener(globalMsgReceiver);
			// 	$rootScope.hasReceiver = true;
			// }
   //  	});

		// 	setRootUser
		$rootScope.teaUser = UserService.getUserAcceptCache();
		$rootScope.unreadNotifyMessage = $rootScope.teaUser.new_message_count;
	});

	$scope.goToStoreList = function () {
		$state.go('store-list');
	};

	$scope.goToLast = function () {
		$state.go('product-last');
	};

	$scope.goToTao = function () {
		$state.go('product-tao');
	};

	$scope.goToActivity = function () {
		$state.go('product-activity');
	};

	$scope.goto_product_info = function (product_id) {
		$state.go('product-info', { product_id: product_id });
	};
}).controller('StoreListBaseCtrl', function ($scope, $state) {}).controller('StoreListCtrl', function ($scope, $state, TeaFriendsPageSvc) {

	$scope.back = function () {
		$state.go('tab.main');
	};

	function chunk(arr, size) {
		var newArr = [];
		for (var i = 0; i < arr.length; i += size) {
			newArr.push(arr.slice(i, i + size));
		}
		return newArr;
	}

	var myData = TeaFriendsPageSvc.fetchStoreData();
	// $scope.chunkedData = chunk(myData, 2);

	$scope.gotoStore = function () {
		$state.go('store');
	};
}).controller('TeaFriendsCtrl', function ($scope, $state, TeaFriendsPageSvc, MsgService, HttpService, UserService, $rootScope) {
	$scope.groupList = [];
	$scope.userList = [];

	$scope.init = function () {
		if (!MsgService.isConnected) {
			MsgService.initRongCloud();
		}

		$scope.groupList();
	};

	$scope.groupList = function () {

    var callback = {
      success: function success(data) {
        $scope.dataGroupList = data.result;

				$rootScope.getUnreadNumber();

				getGroupConversationList();

        var groups = [];
        for (var i = 0; i<data.result.length; i++) {

        	if (isIOS) {
				groups.push({
		            groupId: data.result[i].id,
		            groupName: data.result[i].name,
		            portraitUrl: data.result[i].logo
		          });
			} else {
				groups.push({
		            id: data.result[i].id,
		            name: data.result[i].name,
		            portraitUrl: data.result[i].logo
		          });
			}

        }

        if (!MsgService.isConnected) {
        	return;
        }

		var isIOS = ionic.Platform.isIOS();


        // 同步
        RongCloudLibPlugin.syncGroup({
          groups: groups
        }, function (ret, err) {
        	if (err) {
        		console.log(JSON.stringify(err));
        	}
        	console.log('sync compele');
        });
      },
      failed: function failed() {}
    };

		var user = UserService.getUserAcceptCache(true);

    HttpService({ name: 'group/my', params: {user_id: user.id}, callback: callback });
		// HttpService({ name: 'group/list', params: {}, callback: callback });
  };

	var getGroupConversationList = function() {
		// get 活跃的茶群
		RongCloudLibPlugin.getConversationList(function (ret, err) {

			$scope.$apply(function () {
				//          alert(JSON.stringify(ret.result));
				console.log(JSON.stringify(ret.result));
				var conversationList = ret.result;
				for (var i = 0; i < conversationList.length; i++) {

					if (conversationList[i].conversationType === 'GROUP') {

						var conversation = conversationList[i];

						for( var pos = 0; pos < $scope.dataGroupList.length; pos++) {
							if (conversation.targetId == $scope.dataGroupList[pos].id) {
								$scope.dataGroupList[pos].unread = conversation.unreadMessageCount;
								$scope.dataGroupList[pos].latestMessage = conversation.latestMessage;
								$scope.dataGroupList[pos].isImage = conversation.objectName == 'RC:ImgMsg'
							}
						}
					}
				}
			});
		});
	};

	// console.log('state = tab.friends ' + $state.is('tab.friends'));

	// when new msg come refresh list
	// 刷新列表
		// console.log('set onReceiveListener');
		// var receiveListener = function(ret, err) {
		// 	console.log('new msg');
		//
		// 	if (err) {
		// 		console.log(JSON.stringify(err));
		// 		return;
		// 	}
		//
		// 	// 显示数字更新
		// 	var unreadCallback = {
		// 		success: function success(msg, group) {
		// 			$rootScope.changeNewMsg(msg, group);
		// 		}
		// 	};
		//
		// 	MsgService.getUnreadNumber(unreadCallback)
		// 	if ($state.is('tab.friends')) {
		// 		$scope.groupList();
		// 	} else if ($state.is('account-msg')){
		// 		$scope.initPrivateConversation();
		// 	}
		// };
		// RongCloudLibPlugin.setOnReceiveMessageListener(receiveListener);

		var receiverModel = {};
		if ($state.is('tab.friends')) {
			receiverModel.name = 'tab.friends';
			receiverModel.receiver = function(ret) {
				console.log('tab.friends listener on');
				if ($state.is('tab.friends')) {
					$scope.groupList();


				}
			};
		} else if ($state.is('account-msg')){
			receiverModel.name = 'account-msg';
			receiverModel.receiver = function(ret) {
				console.log('account-msg listener on is account-msg = ' + $state.is('account-msg'));
				if ($state.is('account-msg')) {
					$scope.initPrivateConversation();
				}
			};
		}
		$rootScope.addReceiver(receiverModel);

	// $scope.$on("$destroy", function() {
	// 	$rootScope.setListener();
	// });

	$scope.initPrivateConversation = function () {
		RongCloudLibPlugin.getConversationList(function (ret, err) {

			$scope.$apply(function () {
				//          alert(JSON.stringify(ret.result));
				console.log(JSON.stringify(ret.result));
				var conversationList = ret.result;
				$scope.userList = [];
				for (var i = 0; i < conversationList.length; i++) {

					if (conversationList[i].conversationType === 'PRIVATE') {

						conversationList[i].latestMessage.extra = JSON.parse(conversationList[i].latestMessage.extra);
						conversationList[i].receivedTime = MsgService.timeFormat(conversationList[i].receivedTime, 'yyyy-MM-dd HH:mm:ss');
						conversationList[i].isImage = conversationList[i].objectName == 'RC:ImgMsg'

						$scope.userList.push(conversationList[i]);

						loadUserInfo(conversationList[i].targetId);
					}
				}
			});
		});
	};

	var loadUserInfo = function(id) {
		var loginUser = UserService.getUserAcceptCache(true);

		var userCallback = {
			success: function success(user) {
				for( var pos = 0; pos<$scope.userList.length; pos++) {
					console.log('user_id = ' + user.id + ' $scope.userList[pos].targetId ' + $scope.userList[pos].targetId);
					if (user.id === $scope.userList[pos].targetId) {
						$scope.userList[pos].latestMessage.extra = user;
					}
				}
			},
			failed: function failed(err) {}
		};

		HttpService({ name: 'user/show', params: { target_id: id, user_id: loginUser.id }, callback: userCallback });

	};


	$scope.goToChatPage = function(id, unreadCount) {
		// 之前调用 init 和 connect 的代码省略
		if (unreadCount)
			$rootScope.newMessage = $rootScope.newMessage - unreadCount;

		if ($rootScope.newMessage<0) $rootScope.newMessage = 0;

		RongCloudLibPlugin.clearMessagesUnreadStatus({
		        conversationType: 'PRIVATE',
		        targetId: id,
		    }, function (ret, err) {
		        // alert(ret.status);
		});

		UserService.goToChatPage(id);
	};

	$scope.goToChatGroup = function(id, unreadCount) {

		if (unreadCount)
			$rootScope.newGroupMessage = $rootScope.newGroupMessage - unreadCount;

		if ($rootScope.newGroupMessage<0) $rootScope.newGroupMessage = 0;

		RongCloudLibPlugin.clearMessagesUnreadStatus({
		    conversationType: 'GROUP',
		    targetId: id,
	    }, function (ret, err) {
	        // alert(ret.status);
		});

	    $state.go('chat_group', { id: id });
	};

	$scope.show_friends_list_view = function () {
		$state.go('friends_list');
	};

	$scope.goToGroupList = function () {
		$state.go('group_list');
	};

	$scope.goToTeaFriendsRank = function () {
		$state.go('tea_frends_rank');
	};

	$scope.goToTeaFriendsRecommend = function () {
		$state.go('recommend_tea_friends');
	};
});
